import dayjs from '../miniprogram_npm/dayjs/index'
import Toast from '../miniprogram_npm/@vant/weapp/toast/toast'

export const timeDifference = function (time) {
  const startTime = dayjs(time * 1000).format('YYYY-MM-DD')
  const datetime = dayjs().format('YYYY-MM-DD')
  let timeText = ''
  let minute = 0
  let hours = 0
  const seconds = Date.now() / 1000
  // 同一天
  if (startTime === datetime) {
   
    minute = parseInt((seconds - time) / 60)
    hours = parseInt((seconds - time) / 60 / 60)

    if (minute <= 10) {
      timeText = '刚刚'
    } else if (10 < minute && minute <= 60) {
      timeText = `${minute}分钟前`

    } else if (60 < minute && minute <= 60 * 12) {
      timeText = `${hours}小时前`

    } else if (60 * 12 < minute) {
      timeText = `今天${dayjs(time * 1000).format('HH-mm')}`

    }
  }else {
    const times = seconds - time
    const day = parseInt(times / 60 / 60 / 24)
    if (day >= 3) {
      timeText = dayjs(time * 1000).format('YYYY-MM-DD')
    } else if(day >= 1) {
      timeText = `${day}天前`
    }else {
      timeText = `1天前`
    }

  }
  return timeText

}
// 手机号
export const checkPhone = function(phone) {
  return /^1[3456789]\d{9}$/.test(phone)
}
// 邮件
export const checkEmail = function(email) {
  return /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)
}
// 电话  不带 - 
export const checkTelPhone = function(tel) {
  return /^\d{3}\d{8}$|^\d{4}\d{7,8}$/.test(tel)
}
// 网址
export const  checkUrl = function (urlString){
  const reg =/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
  return reg.test(urlString)
}
export const positive = function(str) {
  return /^(\d|[1-9]\d+)(\.\d+)?$/.test(str)
}
/*函数防抖*/
export const debounce = function (fn, awit = 200) {
  let timer;
  return function() {
    clearTimeout(timer);
    const context = this;
    const args = arguments;//保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
    timer = setTimeout(function() {
      fn.call(context,args);
    }, awit);
  };
}
// 富文本
export const formatRichText = function (html) {
  const imageResizeParams = getApp().imageResizeParams
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
   // console.log(match)
    match = match.replace(/style=""/gi, '')
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });

  let baseurl = getApp().imageURL
  //newContent = newContent.replace(/picdata\/data/g,baseurl)

  console.log(newContent)
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
    return match;
  });

  newContent = newContent.replace(/<br[^>]*\/>/gi, '');

  const regex = new RegExp('<img', 'gi')
  // const delImageStyleReg =  /(?<=\" )style=\".*?"/gi
  //const delImageStyleReg = new RegExp('(?<=\\" )style=\\".*?"','gi')
  //newContent = newContent.replace(delImageStyleReg, '')
  newContent = newContent.replace(regex ,'<img style="max-width:100%;width:100%;height:auto;display:block"')

  const srcREG = /<img [^>]*src=['"]([^'"]+)[^>]*>/gi
  const srcArr = []
  let htmlStr = ''
  if(newContent.includes('<img')) {
    newContent.replace(srcREG,  (match, capture) => {
      //console.log(capture);
      srcArr.push(capture)
      if(!html.includes(capture + imageResizeParams)) {
        htmlStr = newContent.replace( new RegExp(capture, 'gm'), capture + imageResizeParams )
      }
      if(capture.substr(0,7)=='picdata' || capture.substr(0,8)=='/picdata' ){
        htmlStr = newContent.replace( new RegExp(capture, 'gm'), baseurl+capture )
      }
    });
    srcArr.forEach(item => {
      if((htmlStr.includes(item) &&　!htmlStr.includes(item + imageResizeParams))) {
        htmlStr =  htmlStr.replace( item, item + imageResizeParams )
      }
    })
  }else {
    htmlStr = newContent

  }

  return htmlStr;
}

//验证非负整数,可以为0
export const validatePositiveHasZero = function validate_positive_haszero(value){
  const reg = /^[1-9](\d+)?|0$/;
  return reg.test(value)
}
// 身份证
export const idCard = function (idcard) {
  const reg = /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0[1-9]|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/
  return reg.test(idcard)
}

export const checkForm = function( form ){
  let flag = true;
  for( let i=0; i<form.length; i++ ){
    flag = true;
    if( form[i].rule ){
      if( form[i].rule.toLowerCase().indexOf('integer')>-1 ){
        if( form[i].value ){
          flag = validatePositiveHasZero(form[i].value);
          if( !flag ){
            Toast('请输入数字')
            break;
          } 
        }
      }
      if( form[i].rule.toLowerCase().indexOf('in:')>-1 ){
        if( form[i].index ){
          let ss = form[i].rule.substr(3).split(',');
          let id = form[i].value[form[i].index].id;
          console.log(id)
          console.log(ss)
          flag =  ss.includes(id);
          if( !flag ){
            Toast(form[i].cn_name+'的值不在范围内')
            break;
          } 
        }
      }
      if( form[i].rule.toLowerCase().indexOf('max:')>-1 ){
        if( form[i].value ){
          let ss = form[i].rule.substr(4);
          let len = parseInt(ss);
          if( form[i].value.length>len ){
            Toast('超出最大长度'+len)
            flag = false;
            break;
          }
        }
      }
      if( form[i].rule.toLowerCase().indexOf('idcard')>-1 ){
        if( form[i].value ){
          flag = idCard(form[i].value);
          if( !flag ){
            Toast('输入的身份证号不正确')
            break;
          }
        }
      }
      if( form[i].rule.toLowerCase().indexOf('email')>-1 ){
        if( form[i].value ){
          flag = checkEmail(form[i].value);
          if( !flag ){
            Toast('输入的email格式不正确')
            break;
          }
        }
      }
      if( form[i].rule.toLowerCase()=='url' ){
        if( form[i].value ){
          flag = checkUrl(form[i].value);
          if( !flag ){
            Toast('输入的url格式不正确')
            break;
          }
        }
      }
      if( form[i].rule.toLowerCase()=='mobilephone' ){
        if( form[i].value ){
          flag = checkTelPhone(form[i].value);
          if( !flag ){
            Toast('输入的'+form[i].cn_name+'格式不正确')
            break;
          }
        }
      }
      if( form[i].rule.toLowerCase()=='mobile' ){
        if( form[i].value ){
          flag = checkPhone(form[i].value);
          if( !flag ){
            Toast('输入的'+form[i].cn_name+'格式不正确')
            break;
          }
        }
      }
      if( form[i].rule.toLowerCase()=='phone' ){
        if( form[i].value ){
          flag = checkTelPhone(form[i].value);
          if( !flag ){
            Toast('输入的'+form[i].cn_name+'格式不正确')
            break;
          }
        }
      }
    }
  }
  return flag;
}
export const GATCard = function(card) {
  const HongKong = /^[a-zA-Z]\d{6}\([\dA]\)$/
  const Macao =  /^[1|5|7]\d{6}[(\d)]{3}$/
  const Taiwan = /^[a-zA-Z][0-9]{9}$/
  return HongKong.test(card) && Macao.test(card) && Taiwan.test(card)
  
}